package com.chexiehui.jc.mvp.car;

import com.chexiehui.jc.AppApplication;
import com.chexiehui.jc.base.ApiCallback;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BasePage;
import com.chexiehui.jc.base.BasePresenter;
import com.chexiehui.jc.entity.CarInfo;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;

/**
 * @Description 车型对比
 * @Auth SongJun
 * @Date 2020/05/21 00:18
 **/
public class CarModelComparePresenter extends BasePresenter<CarModelCompareCovenant.View, CarModelCompareCovenant.Stores>
        implements CarModelCompareCovenant.Presenter {

    public CarModelComparePresenter(CarModelCompareCovenant.View view) {
        attachView(view);
    }

    @Override
    public void getList(int pageNum) {
        addSubscription(Observable.create((ObservableOnSubscribe<BaseModel<BasePage<CarInfo>>>) emitter -> {
            try {
                long count = AppApplication.getInstances().getCarInfoDao().queryBuilder().count();
                List<CarInfo> list = AppApplication.getInstances().getCarInfoDao().queryBuilder().offset((pageNum - 1) * 10).limit(10).list();
                BasePage<CarInfo> page = new BasePage<>();
                page.setItems(list);
                page.setTotalRecordCount((int) count);
                BaseModel<BasePage<CarInfo>> model = new BaseModel<>(0, "成功");
                model.setData(page);
                emitter.onNext(model);
            } catch (Exception e) {
                e.printStackTrace();
                emitter.onError(e);
            }
        }), new ApiCallback<BaseModel<BasePage<CarInfo>>>(mvpView) {
            @Override
            public void onSuccess(BaseModel<BasePage<CarInfo>> model) {
                mvpView.onGetListSuccess(model);
            }

            @Override
            public void onFailure(int code, String msg) {
                mvpView.onGetListFailure(new BaseModel<>(code, msg));
            }
        });
    }

    @Override
    public void doDelete(List<String> keys) {
        mvpView.showLoading("正在删除");
        addSubscription(Observable.create((ObservableOnSubscribe<BaseModel<Object>>) emitter -> {
            try {
                AppApplication.getInstances().getCarInfoDao().deleteByKeyInTx(keys);
                BaseModel<Object> model = new BaseModel<>(0, "删除成功");
                emitter.onNext(model);
            } catch (Exception e) {
                e.printStackTrace();
                emitter.onError(e);
            }
        }), new ApiCallback<BaseModel<Object>>(mvpView) {
            @Override
            public void onSuccess(BaseModel<Object> model) {
                mvpView.hide();
                mvpView.onDoDeleteSuccess(model);
            }

            @Override
            public void onFailure(int code, String msg) {
                mvpView.hide();
                mvpView.onDoDeleteFailure(new BaseModel<>(code, "删除失败"));
            }
        });
    }


}